package com.tyrone.concurrent.concurrentUtils;

import java.util.Map;
import java.util.concurrent.*;

/**
 * CyclicBarrier的应用场景
 * 计算Excel中每个shell的中的值，然后再求取平均值
 * @author Tyrone
 * @date 2021/12/22 18:27
 */
public class BankWaterService implements Runnable{
    /**
     * 定义了四个shell且全部线程到达同步点后，执行BankWaterService的run方法
     */
    CyclicBarrier cyclicBarrier = new CyclicBarrier(4,this);

    private Executor executor = Executors.newFixedThreadPool(4);

    private ConcurrentHashMap<String,Integer> sheetBankWaterCount = new ConcurrentHashMap<>();

    private void count() {
        for (int i = 0; i < 4; i++) {
            executor.execute(()->{
                System.out.println("正在计算每个Sheet的平均值");
                sheetBankWaterCount.put(Thread.currentThread().getName(), 20);
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });

        }
    }
    @Override
    public void run() {
        int result = 0 ;
        for (Map.Entry<String, Integer> sheet : sheetBankWaterCount.entrySet()) {
            result +=sheet.getValue();
        }
        sheetBankWaterCount.put("result",result);
        System.out.println(result);
    }

    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        BankWaterService bankWaterService = new BankWaterService();
        bankWaterService.count();
    }

}
